var gulp = require('gulp'),
    livereload = require('gulp-livereload'), // 网页自动刷新（文件变动后即时刷新页面）
    webserver = require('gulp-webserver'),
    postcss = require('gulp-postcss'),
    autoprefixer = require('autoprefixer'),
    csslint = require('gulp-csslint'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    minifycss = require('gulp-clean-css'),
    minifyhtml = require('gulp-minify-html'),
    shell = require('gulp-shell'),
    imagemin = require('gulp-imagemin'),
    useref = require('gulp-useref'),
    rev = require('gulp-rev'),
    revReplace = require('gulp-rev-replace'),
    revCollector = require('gulp-rev-collector'),
    del = require('del'),
    runSequence = require('run-sequence'),
    stripDebug = require('gulp-strip-debug'),
    plumber = require('gulp-plumber'),
    gulpif = require('gulp-if'),
    argv = require('yargs'),
    babel = require("gulp-babel");
    // removeUseStrict = require("gulp-remove-use-strict");


var argv = argv.argv;
var baseDir = './src';
var outputDir = './dist';
var tmpDir = './tmp';
var paths = {
    styles: baseDir + 'styles/*',
    scripts: baseDir + '/scripts',
    // image
    images: baseDir + '/assets/images/*',
    // fonts
    fonts: baseDir + '/assets/fonts/*',
    // 公用合并的CSS项
    concatCSS: {
        app: {
            default: [
                baseDir + '/styles/app/default/base.css', // 基础
                baseDir + '/styles/app/default/index.css', // 首页
                baseDir + '/styles/app/default/login.css', // 登录
                baseDir + '/styles/app/default/work.css', // 工作台
                baseDir + '/styles/app/default/organization.css', // 组织架构
                baseDir + '/styles/app/default/const_item.css', // 费项配置
                baseDir + '/styles/app/default/res_manage.css', // 资源列表
                baseDir + '/styles/app/default/resource.css', // 项目配置
                baseDir + '/styles/app/default/user_manage.css', // 用户管理
                baseDir + '/styles/app/default/rent.css', // 租控管理
                baseDir + '/styles/app/default/contract.css', // 合同管理
                baseDir + '/styles/app/default/customer.css', // 招商管理
                baseDir + '/styles/app/default/bill.css', // 账单
                baseDir + '/styles/app/default/report_ui.css', // 统计报表
                baseDir + '/styles/app/default/print.css', // 账单打印
                baseDir + '/styles/app/default/JYbill_print.css', // 建原账单打印
                baseDir + '/styles/app/default/report_bi.css', // 统计报表
                baseDir + '/styles/app/default/withdraw.css', // 退租管理
                baseDir + '/styles/app/default/flow.css', // 工作流
                baseDir + '/styles/app/default/working_group.css', // 工作组
                baseDir + '/styles/app/default/price.css', // 底价管理
                baseDir + '/styles/app/default/wx_message.css', // 微信消息
                baseDir + '/styles/app/default/wx_GZHconfig.css', // 微信公众号
                baseDir + '/styles/app/default/print_template.css', // 打印模版
                baseDir + '/styles/app/default/user_list.css', // 组织架构
                baseDir + '/styles/app/default/ddconfig.css', //钉钉团队配置
                baseDir + '/styles/app/default/following.css', //项目分派
                baseDir + '/styles/app/default/projectDetail.css', //项目详情
            ],
            blue: [
                baseDir + '/styles/app/blue/base.css',
                baseDir + '/styles/app/blue/components.css',
                baseDir + '/styles/app/blue/index.css',
                baseDir + '/styles/app/blue/login.css',
                baseDir + '/styles/app/blue/work.css',
                baseDir + '/styles/app/blue/organization.css',
                baseDir + '/styles/app/blue/const_item.css',
                baseDir + '/styles/app/blue/res_manage.css',
                baseDir + '/styles/app/blue/resource.css',
                baseDir + '/styles/app/blue/user_manage.css',
                baseDir + '/styles/app/blue/rent.css',
                baseDir + '/styles/app/blue/contract.css',
                baseDir + '/styles/app/blue/customer.css',
                baseDir + '/styles/app/blue/bill.css',
                baseDir + '/styles/app/blue/report_ui.css',
                baseDir + '/styles/app/blue/print.css',
                baseDir + '/styles/app/blue/JYbill_print.css',
                baseDir + '/styles/app/blue/report_bi.css',
                baseDir + '/styles/app/blue/withdraw.css',
                baseDir + '/styles/app/blue/flow.css',
                baseDir + '/styles/app/blue/working_group.css',
                baseDir + '/styles/app/blue/price.css',
                baseDir + '/styles/app/blue/wx_message.css',
                baseDir + '/styles/app/blue/wx_GZHconfig.css',
                baseDir + '/styles/app/blue/print_template.css',
                baseDir + '/styles/app/blue/user_list.css',
                baseDir + '/styles/app/blue/ddconfig.css',
                baseDir + '/styles/app/blue/following.css',
                baseDir + '/styles/app/blue/projectDetail.css',
            ],
            winered: [
                baseDir + '/styles/app/winered/base.css',
                baseDir + '/styles/app/winered/index.css',
                baseDir + '/styles/app/winered/login.css',
                baseDir + '/styles/app/winered/work.css',
                baseDir + '/styles/app/winered/organization.css',
                baseDir + '/styles/app/winered/const_item.css',
                baseDir + '/styles/app/winered/res_manage.css',
                baseDir + '/styles/app/winered/resource.css',
                baseDir + '/styles/app/winered/user_manage.css',
                baseDir + '/styles/app/winered/rent.css',
                baseDir + '/styles/app/winered/contract.css',
                baseDir + '/styles/app/winered/customer.css',
                baseDir + '/styles/app/winered/bill.css',
                baseDir + '/styles/app/winered/report_ui.css',
                baseDir + '/styles/app/winered/print.css',
                baseDir + '/styles/app/winered/JYbill_print.css',
                baseDir + '/styles/app/winered/report_bi.css',
                baseDir + '/styles/app/winered/withdraw.css',
                baseDir + '/styles/app/winered/flow.css',
                baseDir + '/styles/app/winered/working_group.css',
                baseDir + '/styles/app/winered/price.css',
                baseDir + '/styles/app/winered/wx_message.css',
                baseDir + '/styles/app/winered/wx_GZHconfig.css',
                baseDir + '/styles/app/winered/print_template.css',
                baseDir + '/styles/app/winered/user_list.css',
                baseDir + '/styles/app/winered/ddconfig.css',
                baseDir + '/styles/app/winered/following.css',
                baseDir + '/styles/app/winered/projectDetail.css',
            ],
            yellow: [
                baseDir + '/styles/app/yellow/base.css',
                baseDir + '/styles/app/yellow/index.css',
                baseDir + '/styles/app/yellow/login.css',
                baseDir + '/styles/app/yellow/work.css',
                baseDir + '/styles/app/yellow/organization.css',
                baseDir + '/styles/app/yellow/const_item.css',
                baseDir + '/styles/app/yellow/res_manage.css',
                baseDir + '/styles/app/yellow/resource.css',
                baseDir + '/styles/app/yellow/user_manage.css',
                baseDir + '/styles/app/yellow/rent.css',
                baseDir + '/styles/app/yellow/contract.css',
                baseDir + '/styles/app/yellow/customer.css',
                baseDir + '/styles/app/yellow/bill.css',
                baseDir + '/styles/app/yellow/report_ui.css',
                baseDir + '/styles/app/yellow/print.css',
                baseDir + '/styles/app/yellow/JYbill_print.css',
                baseDir + '/styles/app/yellow/report_bi.css',
                baseDir + '/styles/app/yellow/withdraw.css',
                baseDir + '/styles/app/yellow/flow.css',
                baseDir + '/styles/app/yellow/working_group.css',
                baseDir + '/styles/app/yellow/price.css',
                baseDir + '/styles/app/yellow/wx_message.css',
                baseDir + '/styles/app/yellow/wx_GZHconfig.css',
                baseDir + '/styles/app/yellow/print_template.css',
                baseDir + '/styles/app/yellow/user_list.css',
                baseDir + '/styles/app/yellow/ddconfig.css',
                baseDir + '/styles/app/yellow/following.css',
                baseDir + '/styles/app/yellow/projectDetail.css',
            ]
        },
        libs: [
            baseDir + '/styles/libs/*.css'
        ]
    },
    // 业务JS
    businessJS: {},
    // 公用JS项
    commonJS: {
        route: [baseDir + '/scripts/routes.js'], // 路由
        libs: [baseDir + '/scripts/libs/*'], // 第三方组件
        app: [baseDir + '/scripts/app/*'], // 业务组件
    },
    // 公用组件
    components: baseDir + '/components/**/*',
    // 公用指令
    directives: baseDir + '/directives/**/*',
    // css rev 替换
    rev: {
        js: [
            tmpDir + '/rev/js/app/rev-manifest.json',
            tmpDir + '/rev/js/libs/rev-manifest.json',
            tmpDir + '/rev/js/route/rev-manifest.json'
        ]
    },
    // 复制处理
    copy: {
        favicon: [
            baseDir + '/favicon_default.ico',
            baseDir + '/favicon_blue.ico',
            baseDir + '/favicon_yellow.ico',
            baseDir + '/favicon_winered.ico'
        ]
    },
    // 页面
    pages: {
        billTemplate: [baseDir + '/modules/bill/page/template/*'], // 账单模块
    },
    // 页面
    commonPages: [
        baseDir + '/index.html',
        baseDir + '/ddAdminLogin.html',
        baseDir + '/goToWxAuth.html',
        baseDir + '/ddlogin.html',
        baseDir + '/loading.html',
        baseDir + '/login.html',
        baseDir + '/ssoLogin.html',
    ]

}

var pathsName = ['bill', 'contract', 'customer', 'rent', 'report_bi', 'report_ui', 'system_config', 'user', 'withdraw', 'workbench', 'flow',
'working_group', 'price', 'wx_message', 'wx_gzh', 'print_template', 'projectConfig', 'market','voucher', 'jwk', 'contratchange', 'visitor', 'custom'];

for (let i = 0; i < pathsName.length; i++) {
	paths.pages[pathsName[i]] = [baseDir + '/modules/'+pathsName[i]+'/page/*']
	paths.businessJS[pathsName[i]] = [baseDir + '/modules/'+pathsName[i]+'/scripts/*']
}

// 配置postcss的插件项
var processors = [
    autoprefixer({ browsers: ["Chrome > 31", "ff > 31", "ie >= 9"] })
];

// 压缩业务JS
var businessJsArr = []
// 业务页面

var businessPageArr = []
for (let key in paths.pages) {
	businessPageArr.push(key+'-page')
	if (key.indexOf('billTemplate') == -1) {
		businessJsArr.push(key+'-js')
		gulp.task(key + '-js', function() {
			return gulp.src(paths.businessJS[key])
				// .pipe(stripDebug())
				// .pipe(babel())
				// .pipe(uglify())
				.pipe(gulp.dest('./dist/modules/'+key+'/scripts'))
		})

		gulp.task(key+'-page', function() {
			return gulp.src(paths.pages[key])
				// .pipe(minifyhtml({
				// 	removeComments: false, //清除HTML注释
				// 	// collapseWhitespace: true, //压缩HTML
				// 	// minifyJS: true, //压缩页面JS
				// 	// minifyCSS: true //压缩页面CSS
				// }))
				.pipe(gulp.dest('./dist/modules/'+key+'/page'))
		})
	}
}

gulp.task('billTemplate-page', function() {
    return gulp.src(paths.pages.billTemplate)
        // .pipe(minifyhtml({
        //     removeComments: false, //清除HTML注释
        //     // collapseWhitespace: true, //压缩HTML
        //     // minifyJS: true, //压缩页面JS
        //     // minifyCSS: true //压缩页面CSS
        // }))
        .pipe(gulp.dest('./dist/modules/bill/page/template'))
})

gulp.task('minify-Business-js', businessJsArr)

gulp.task('business-page', businessPageArr)

gulp.task('common-page', function() {
    return gulp.src(paths.commonPages)
        .pipe(minifyhtml({
            removeComments: false, //清除HTML注释
            collapseWhitespace: false, //压缩HTML
            minifyJS: true, //压缩页面JS
            minifyCSS: true //压缩页面CSS
        }))
        .pipe(gulp.dest(outputDir))
})
gulp.task('page', ['business-page', 'common-page'])

// 压缩公用组件
gulp.task('minify-components-js', function() {
    return gulp.src(paths.components)
        // .pipe(stripDebug())
        // .pipe(babel())
        // .pipe(uglify())
        .pipe(gulp.dest('./dist/components'))
})

// 压缩公用指令
gulp.task('minify-directives-js', function() {
    return gulp.src(paths.directives)
        // .pipe(stripDebug())
        // .pipe(babel())
        // .pipe(uglify())
        .pipe(gulp.dest('./dist/directives'))
})

// 压缩第三方JS
gulp.task('minify-libs-js', function() {
    return gulp.src(paths.commonJS.libs)
        // .pipe(stripDebug())
        // .pipe(babel())
        // .pipe(uglify())
        .pipe(gulp.dest('./dist/scripts/libs'))
})

// 压缩公用JS
gulp.task('minify-common-js', function() {
    return gulp.src(paths.commonJS.app)
        // .pipe(stripDebug())
        // .pipe(babel())
        // .pipe(uglify())
        .pipe(gulp.dest('./dist/scripts/app'))
})

// route.js
gulp.task('js', ['minify-Business-js', 'minify-libs-js', 'minify-common-js','minify-components-js','minify-directives-js'], function() {
    return gulp.src(paths.commonJS.route)
        // .pipe(babel())
        // .pipe(uglify())
        .pipe(gulp.dest('./dist/scripts/'))
})


// 合并业务CSS
// 默认肤色  绿色
gulp.task('concat-default-css', function() {
    return gulp.src(paths.concatCSS.app.default)
        .pipe(plumber())
        .pipe(postcss(processors))
        .pipe(minifycss())
        .on('error', function(error) {
            this.end()
        })
        .pipe(concat('default.min.css'))
        .pipe(gulp.dest(outputDir + '/styles/app/default'))
        .pipe(gulpif(argv.dev, gulp.dest(baseDir + '/styles/app/default')))
})

// 蓝色
gulp.task('concat-blue-css', function() {
    return gulp.src(paths.concatCSS.app.blue)
        .pipe(plumber())
        .pipe(postcss(processors))
        .pipe(minifycss())
        .on('error', function(error) {
            this.end()
        })
        .pipe(concat('blue.min.css'))
        .pipe(gulp.dest(outputDir + '/styles/app/blue'))
        .pipe(gulpif(argv.dev, gulp.dest(baseDir + '/styles/app/blue')))
})

// 酒红色
gulp.task('concat-winered-css', function() {
    return gulp.src(paths.concatCSS.app.winered)
        .pipe(plumber())
        .pipe(postcss(processors))
        .pipe(minifycss())
        .on('error', function(error) {
            this.end()
        })
        .pipe(concat('winered.min.css'))
        .pipe(gulp.dest(outputDir + '/styles/app/winered'))
        .pipe(gulpif(argv.dev, gulp.dest(baseDir + '/styles/app/winered')))
})

// 黄色
gulp.task('concat-yellow-css', function() {
    return gulp.src(paths.concatCSS.app.yellow)
        .pipe(plumber())
        .pipe(postcss(processors))
        .pipe(minifycss())
        .on('error', function(error) {
            this.end()
        })
        .pipe(concat('yellow.min.css'))
        .pipe(gulp.dest(outputDir + '/styles/app/yellow'))
        .pipe(gulpif(argv.dev, gulp.dest(baseDir + '/styles/app/yellow')))
})

// 公用CSS
gulp.task('concat-libs-css', function() {
    return gulp.src(paths.concatCSS.libs)
        .pipe(minifycss())
        .pipe(gulp.dest(outputDir + '/styles/libs'))
})

// CSS处理
gulp.task('css', ['concat-default-css', 'concat-blue-css', 'concat-winered-css', 'concat-yellow-css', 'concat-libs-css'])

// 打包图片
gulp.task('minifyimage', function() {
    return gulp.src(paths.images)
        // .pipe(imagemin())
        .pipe(gulp.dest(outputDir + '/assets/images'))
})

gulp.task('minifyimage2', function() {
    return gulp.src('./src/assets/images/location/*')
        // .pipe(imagemin())
        .pipe(gulp.dest(outputDir + '/assets/images/location'))
})


// 打包字体文件
gulp.task('fonts', function() {
    return gulp.src(paths.fonts)
        .pipe(gulp.dest(outputDir + '/assets/fonts'))
})

// 清理文件
gulp.task('clean', function(cb) {
    return del([outputDir, tmpDir], cb);
})
gulp.task('dev-clean', function(cb) {
    return del([
        baseDir + '/styles/app/blue/blue.min.css',
        baseDir + '/styles/app/default/default.min.css',
        baseDir + '/styles/app/winered/winered.min.css',
        baseDir + '/styles/app/yellow/yellow.min.css',
    ], cb)
})

// 网站图标和入口页
gulp.task('copy', function() {
    gulp.src(paths.copy.favicon)
        .pipe(gulp.dest(outputDir))
})

// 注册任务
gulp.task('webserver', function() {
    gulp.src('./src') // 服务器目录（.代表根目录）
        .pipe(webserver({
            livereload: false,
            open: true
        }));
});

// 开发环境
gulp.task('dev', function() {
    runSequence('dev-clean', 'css')
})

// 生产环境
gulp.task('default', function() {
    runSequence('clean', ['minifyimage', 'minifyimage2', 'fonts', 'copy'], 'js', 'css', 'page')
})
